package net.jueb.frameworkDemo.orm.mapdb;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentNavigableMap;

import org.mapdb.CC;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import org.mapdb.Serializer;
import org.mapdb.volume.ByteArrayVol;
import org.mapdb.volume.ByteBufferMemoryVol;
import org.mapdb.volume.Volume;

public class VolumeTest {

	public Volume getVol() throws Exception {
		Volume v =null;
//		File f = File.createTempFile("some", "file");
//		v = MappedFileVol.FACTORY.makeVolume(f.getPath(), false);
//		System.out.println(f);
		v=new ByteBufferMemoryVol(false, CC.PAGE_SHIFT, true, 1024);
//		v=new ByteArrayVol();
		return v;
	}

	public void test() throws Exception {
		Volume v = getVol();
		DB db = DBMaker.volumeDB(v, false).make();
		db.checkThreadSafe();
		Map<Integer, String> map = db.treeMap("collectionName", Serializer.INTEGER, Serializer.STRING).createOrOpen();
		long t = System.currentTimeMillis();
		for (int i = 0; i < 10000; i++) {
			map.put(i, "value:" + i);
		}
		t = System.currentTimeMillis() - t;
		System.out.println(t+":"+v.length());
		t = System.currentTimeMillis();
		db.commit();//提交数据到卷
		map.put(131231, "112233");
		t = System.currentTimeMillis() - t;
		System.out.println(t+":"+v.length());
		System.out.println("map.size():"+map.size());
		t = System.currentTimeMillis();
		ByteArrayOutputStream bos=new ByteArrayOutputStream();
		v.copyTo(bos);
		byte[] data=bos.toByteArray();
		t = System.currentTimeMillis() - t;
		System.out.println(t);
		System.out.println("byte len:"+data.length);
		t = System.currentTimeMillis();
		ByteArrayVol v2=new ByteArrayVol();
		v2.copyFrom(new ByteArrayInputStream(data));
		DB db2 = DBMaker.volumeDB(v2, true).checksumHeaderBypass().make();
		Map<Integer, String> map2 = db2.treeMap("collectionName", Serializer.INTEGER, Serializer.STRING).createOrOpen();
		t =System.currentTimeMillis()-t;
		System.out.println(t);
		System.out.println("map2:"+map2.size());
		System.out.println("map2:"+map2.get(131231));
	}

	public static void main(String[] args) throws Exception {
		new VolumeTest().test();
	}
}
